﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TrainingWorkshop.Model;
using WCFContracts;
using System.ServiceModel;


namespace Presentation
{
    public partial class CourseUpdate : System.Web.UI.Page
    {
        public TrainingWorkshop.Model.CourseList selectedCourse = new TrainingWorkshop.Model.CourseList();
        public static List<Student> oldSelectedStudent = new List<Student>();

        protected IProjectBService service;
        protected ProjectBProxy projectBProxy = new ProjectBProxy();

        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Page.PreLoad"/> event after postback data is loaded into the page server controls but before the <see cref="M:System.Web.UI.Control.OnLoad(System.EventArgs)"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
        /// <remarks></remarks>
        protected override void OnPreLoad(EventArgs e)
        {
            base.OnPreLoad(e);
            service = projectBProxy.GetProjectBService();
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            projectBProxy.Close();
        }

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <remarks></remarks>
        protected void Page_Load(object sender, EventArgs e)
        {
            //get selected course
            this.selectedCourse = (TrainingWorkshop.Model.CourseList)this.Session["SelectedCourse"];

            if (!Page.IsPostBack)
            {
                //bind teacher name in dropdownlist
                bindDropTeacherName();

                //bind Course Level in dropdownlist
                bindDropLevelName();

                //set default value of selected course
                if (this.selectedCourse != null)
                {
                    //set course name
                    this.CourseNameTextBox.Text = this.selectedCourse.CourseName;
                    //set teacher name 
                    int index = 0;
                    foreach (object s in TeacherNameDropDownList.Items)
                    {
                        string teacherName = s.ToString().Trim();

                        if (teacherName == selectedCourse.TeacherName)
                        {
                            TeacherNameDropDownList.SelectedIndex = index;
                        }

                        index++;
                    }
                    //set level name
                    index = 0;
                    foreach (object s in LevelNameDropDownList.Items)
                    {
                        string levelName = s.ToString().Trim();
                        if (levelName == selectedCourse.LevelName)
                        {
                            LevelNameDropDownList.SelectedIndex = index;
                        }
                        index++;
                    }

                    //bind students in listbox
                    bindListBox(selectedCourse.CourseId);
                }

            }

        }

        /// <summary>
        /// Binds the list box.
        /// </summary>
        /// <param name="courseId">The course id.</param>
        /// <remarks></remarks>
        private void bindListBox(int courseId)
        {
            oldSelectedStudent = service.GetStudentListByCourse(courseId);
            bindStudentList(service.GetStudentListsNoInCourse(courseId));
            bindSeletedStudentList(oldSelectedStudent);

        }

        /// <summary>
        /// Binds level name to the dropdownlist .
        /// </summary>
        /// <remarks></remarks>
        private void bindDropLevelName()
        {
            this.LevelNameDropDownList.DataSource = service.GetLevels();
            this.LevelNameDropDownList.DataTextField = "LevelName";
            this.LevelNameDropDownList.DataValueField = "LevelId";
            this.LevelNameDropDownList.DataBind();
        }

        /// <summary>
        /// Binds teacher name to the dropdownlist ..
        /// </summary>
        /// <remarks></remarks>
        private void bindDropTeacherName()
        {

            this.TeacherNameDropDownList.DataSource = service.GetTeachers();
            this.TeacherNameDropDownList.DataTextField = "TeacherName";
            this.TeacherNameDropDownList.DataValueField = "TeacherId";

            this.TeacherNameDropDownList.DataBind();
        }

        //lis of student who does not in course
        private void bindStudentList(List<TrainingWorkshop.Model.Student> StudentsNotInCourse)
        {
            this.AllStudentListBox.DataSource = StudentsNotInCourse;
            this.AllStudentListBox.DataValueField = "StudentId";
            this.AllStudentListBox.DataTextField = "StudentName";
            this.AllStudentListBox.DataBind();

        }
        //list of student who's already in course
        private void bindSeletedStudentList(List<TrainingWorkshop.Model.Student> StudentsInCourse)
        {
            this.SelectedStudentListBox.DataSource = StudentsInCourse;
            this.SelectedStudentListBox.DataTextField = "StudentName";
            this.SelectedStudentListBox.DataValueField = "StudentId";
            this.SelectedStudentListBox.DataBind();
        }


        protected void ToSelected_Click(object sender, EventArgs e)
        {
            //get student to add in selectedlist
            Student toSelected = new Student();
            if (AllStudentListBox.SelectedItem != null)
            {
                ListItem tempToSelect = this.AllStudentListBox.SelectedItem;
                toSelected.StudentName = tempToSelect.Text.ToString().Trim();
                toSelected.StudentId = Convert.ToInt32(tempToSelect.Value);

                //add to SelectedStudent ListBox in view
                SelectedStudentListBox.Items.Add(tempToSelect);

                //remove from student list box in view
                AllStudentListBox.Items.Remove(tempToSelect);
            }
        }

        /// <summary>
        /// Handles the Click event of the CancelSelect control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <remarks></remarks>
        protected void CancelSelect_Click(object sender, EventArgs e)
        {
            //get canceled student
            Student cancelSelected = new Student();
            if (SelectedStudentListBox.SelectedItem != null)
            {
                ListItem tempCancelSelected = this.SelectedStudentListBox.SelectedItem;
                cancelSelected.StudentId = Convert.ToInt32(tempCancelSelected.Value);
                cancelSelected.StudentName = tempCancelSelected.Text.ToString().Trim();

                //add to toSelect students listbox in view
                AllStudentListBox.Items.Add(tempCancelSelected);


                //remove from selected student list in view
                SelectedStudentListBox.Items.Remove(tempCancelSelected);
            }
        }

        /// <summary>
        /// Handles the Click event of the SaveCourse control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <remarks></remarks>
        protected void SaveCourse_Click(object sender, EventArgs e)
        {

            //get course Info

            TrainingWorkshop.Model.Course CourseToSave = new Course(new Teacher(), new Level());
            CourseToSave.CourseId = selectedCourse.CourseId;
            CourseToSave.CourseName = this.CourseNameTextBox.Text.ToString().Trim();
            CourseToSave.CourseStatus = selectedCourse.CourseStatus;
            CourseToSave.Teacher.TeacherName = this.TeacherNameDropDownList.SelectedItem.Text.ToString().Trim();
            CourseToSave.Teacher.TeacherId = Convert.ToInt32(this.TeacherNameDropDownList.SelectedValue);
            CourseToSave.Level.LevelName = this.LevelNameDropDownList.SelectedItem.Text.ToString().Trim();
            CourseToSave.Level.LevelId = Convert.ToInt32(this.LevelNameDropDownList.SelectedValue);

            //get channel access
            ChannelFactory<IProjectBService> ChannelFactory = new ChannelFactory<IProjectBService>("ProjectBClient");

            //* Compare with previous course info
            // * if changed then send to BLL
            // * else do not send
            // * /


            if (selectedCourse != null)
            {
                if ((selectedCourse.CourseName.Trim() != CourseToSave.CourseName)
                        || (selectedCourse.TeacherName.Trim() != CourseToSave.Teacher.TeacherName)
                            || (selectedCourse.LevelName.Trim() != CourseToSave.Level.LevelName))
                {
                    //pass courseToSave to  CourseBusinessUnit in BLL
                    service.UpdateCourse(CourseToSave);
                }

            }

            /**
             * Pass studentlist to CourseDetailBusinessUnit in BLL
             * to implement add to delete students in a certain course
             * */
            List<Student> SelectedStudent = new List<Student>();
            foreach (ListItem l in SelectedStudentListBox.Items)
            {
                Student s = new Student();
                s.StudentId = Convert.ToInt32(l.Value);
                s.StudentName = l.ToString().Trim();
                SelectedStudent.Add(s);
            }

            service.DeleteStudentsFromCourse(selectedCourse.CourseId, oldSelectedStudent);
            service.AddStudentsToCourse(selectedCourse.CourseId, SelectedStudent);

            this.MsgLable.Visible = true;
        }

    }
}